package com.mxy.myapplication.activity;

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;
import com.mxy.myapplication.R;

/**
 * 自定义扫描界面
 */

public class Customer_Scanner_activity extends BaseActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {

    private CaptureManager capture;
    private DecoratedBarcodeView barcodeScannerView;
    private CheckBox turntorch;
    private View back;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_scaner);
        initView(savedInstanceState);
    }

    private void initView(Bundle savedInstanceState) {
        back = findViewById(R.id.back);
        back.setOnClickListener(this);
        turntorch = (CheckBox) findViewById(R.id.turntorch);
        if (hasFlash()) {
            turntorch.setVisibility(View.VISIBLE);
            turntorch.setChecked(false);
            turntorch.setOnCheckedChangeListener(this);
        } else {
            turntorch.setVisibility(View.INVISIBLE);
        }
        barcodeScannerView = (DecoratedBarcodeView) findViewById(R.id.zxing_barcode_scanner);
        capture = new CaptureManager(this, barcodeScannerView);
        capture.initializeFromIntent(getIntent(), savedInstanceState);
        capture.decode();
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        capture.onSaveInstanceState(outState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        capture.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        capture.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        capture.onDestroy();
    }

    @Override
    public void onClick(View v) {
        if(v==back){
            finish();
        }
    }

    /**
     * @return 判断设备是否带有闪光灯
     */
    private boolean hasFlash() {
        return getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if(isChecked){
            barcodeScannerView.setTorchOn();
        }else{
            barcodeScannerView.setTorchOff();
        }
    }
}